package com.lanou.controller;

import com.google.gson.Gson;
import com.lanou.pojo.Tb_user;
import com.lanou.service.SelectService;
import com.lanou.utils.AjaxResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    private SelectService selectService = new SelectService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        boolean check = Boolean.parseBoolean("check");
        response.setContentType("application/json;charset=utf-8");
        AjaxResult ar = new AjaxResult();
        PrintWriter out = response.getWriter();
        Tb_user tbUser = selectService.selectByusername(username,password);
        int id = tbUser.getUid();
        HttpSession session = request.getSession();
        if (tbUser!=null){
            ar.setCode(1000);
            ar.setMsg("登陆成功");
            ar.setData(tbUser);
            session.setAttribute("id",id);
            if (check){
                String uid =session.getId();
                Cookie js = new Cookie("JSESSIONID",uid);
                js.setMaxAge(60*60*24*7);
                response.addCookie(js);
                session.setMaxInactiveInterval(60*60*24*7);
            }
        }else {
            ar.setCode(1001);
            ar.setMsg("登录失败");
        }
        out.write(new Gson().toJson(ar));
        out.close();
    }
}
